<template>
  <div class="kva-container-box">
    <div class="kva-container">
      <home-page-header>
        <div class="kva-from-search">
          <el-form :inline="true" :model="pageInfo">
            <el-form-item>
              <el-button type="primary" icon="Plus">添加用户</el-button>
              <el-button type="danger" icon="Delete" @click="handleBatchDel">删除用户</el-button>
            </el-form-item>
            <el-form-item label="关键词:" style="margin-left: 15px">
              <el-input v-model="pageInfo.keyword" placeholder="请输入搜索关键词..." maxlength="10"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
              <el-button type="warning" icon="Delete" @click="handleClear">清空</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="tableData" @selection-change="handleSelectionChange" style="width: 100%"
                  :height="settings.tableHeight()">
          <el-table-column type="selection" fixed="left" width="30"/>
          <el-table-column fixed prop="id" label="ID" width="80" align="center"/>
          <el-table-column prop="account" label="账号" width="80" align="center"/>
          <el-table-column label="昵称" width="160" align="center">
            <template #default="scope">
              <el-avatar :size="small" :src="scope.row.avatar"></el-avatar>
              <span style="position: absolute;padding-top: 10px;margin-left: 5px">{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" width="120" align="center"/>
          <el-table-column prop="email" label="用户邮箱" width="180" align="center"/>
          <el-table-column label="冻结状态" align="center">
            <template #default="scope">
              <!-- 默认激活状态颜色 active-color="#ff0000"
                   选中状态颜色   inactive-color="#00ff00" -->
              <el-switch
                  v-model="scope.row.enable"
                  inline-prompt
                  size="large"
                  :active-value="2"
                  active-color="#ff0000"
                  active-text="冻结"
                  inactive-color="#00ff00"
                  inactive-text="正常"
                  :inactive-value="1"
                  @change="handleChangeStatus(scope.row,'enable')"
              />
            </template>
          </el-table-column>
          <el-table-column label="删除状态" align="center">
            <template #default="scope">
              <!-- 默认激活状态颜色 active-color="#ff0000"
                   选中状态颜色   inactive-color="#00ff00" -->
              <el-switch
                  v-model="scope.row.isDeleted"
                  inline-prompt
                  size="large"
                  :active-value="1"
                  active-color="#ff0000"
                  active-text="已删除"
                  inactive-color="#00ff00"
                  inactive-text="未删除"
                  :inactive-value="0"
                  @change="handleChangeStatus(scope.row,'is_deleted')"
              />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="160">
            <template #default="scope">
              {{ formatTimeToStr(scope.row.createTime, "yyyy-MM-dd hh:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" width="160">
            <template #default="scope">
              {{ formatTimeToStr(scope.row.updateTime, "yyyy-MM-dd hh:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="240">
            <template #default="{row,$index}">
              <el-button link type="danger" icon="RemoveFilled" @click="handleDelete(row)">删除</el-button>
              <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="success" icon="Switch" @click="handleResetPwd(row)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="kva-page">
          <el-pagination
              v-model:current-page="pageInfo.page"
              v-model:page-size="pageInfo.pageSize"
              :page-sizes="[1,10, 20, 30, 40]"
              small
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </home-page-header>
    </div>
    <!-- 重置密码弹窗 -->
    <reset-password ref="userPwdRef"></reset-password>
  </div>
</template>

<script setup>
import settings from '@/settings';
import {kvaMessage} from "@/utils/kvaMessage.js";
import {LoadSysUserPage,UpdateSysUserStatus, DeleteSysUser ,DeleteSysUserIds} from "@/api/sysUser.js"
import {formatTimeToStr} from '@/utils/date.js'
import ResetPassword from "@/views/app/components/ResetPassword.vue";

// 定义分页属性
const pageInfo = reactive({
  page: 1,
  PageSize: 10,
  keyword: '',
})

// 定义数据容器
const tableData = ref([])
// 定义总数
const total = ref(0)

// 查询用户列表分页信息
const handleLoadData = async () => {
  // 调用系统用户分页接口的方法
  const resp = await LoadSysUserPage(pageInfo)
  tableData.value = resp.data.list
  total.value = resp.data.total
  pageInfo.page = resp.data.page
}

// 点击修改每页大小
const handleSizeChange = (pageSize) => {
  // 改变大小后，从第一页开始重新计算
  pageInfo.page = 1
  // 每页显示多少条数据
  pageInfo.PageSize = pageSize
  // 重新渲染页面
  handleLoadData()
}

// 点击分页改变（翻页）
const handleCurrentChange = (page) => {
  // 当前是第几页
  pageInfo.page = page
  // 重新渲染页面
  handleLoadData()
}

// 修改状态
const handleChangeStatus = async(row,field) => {
  let params = {id:row.id,field}
  if (field == 'enable'){
    params.value = row.enable
  }
  if (field == 'is_deleted'){
    params.value = row.isDeleted
  }

  // 调用修改状态的接口方法
  await UpdateSysUserStatus(params)
  kvaMessage.notifySuccess("状态修改成功！")
}

// 删除单个
const handleDelete = async (row) => {
  const result = await kvaMessage.confirm("删除用户", "您确定要删除吗？")
  if (result === 'confirm') {
    // 调用删除接口
    await DeleteSysUser(row.id)
    kvaMessage.success("删除成功！")
    // 重新渲染数据
    handleLoadData()
  }

}

// 获取删除的ids
const ids = ref([])
// 获取选中批量删除的ids
const handleSelectionChange = (rows) => {
  ids.value = rows.map(row => row.id)
}
// 批量删除
const handleBatchDel = async () => {
  // 如果没有选中的行数，提示
  if (ids.value.length === 0) {
    kvaMessage.warning('请选择一项删除的列进行操作!!!')
    return
  }
  const result = await kvaMessage.confirm("批量删除", '你确定执行【批量删除】吗?')
  if (result === 'confirm') {
    const idsStrings = ids.value.join(',')
    console.log('idsStrings',idsStrings)
    await DeleteSysUserIds(idsStrings)
    kvaMessage.success('批量删除成功!')
    // 重新渲染数据
    handleLoadData()
  }
}


// 编辑
const handleEdit = (row) => {

}

// 重置密码的组件对象
const userPwdRef = ref({})

// 重置密码点击事件
const handleResetPwd = (row) =>{
  userPwdRef.value.handleOpen(row)
}


// 搜索按钮
const handleSearch = () => {
  // 搜索后，重新开始计算
  pageInfo.page = 1
  // 重新渲染页面
  handleLoadData()
}

// 清空按钮
const handleClear = () => {
  // 清空搜索的条件
  pageInfo.keyword = ''
  // 重新渲染页面
  handleLoadData()
}

// 生命周期加载
onMounted(() => {
  handleLoadData()
})

</script>


<style scoped lang="scss">
.kva-container-box {
  padding: 12px 16px;
}

.kva-container {
  padding: 24px;
  background-color: #fff;
  border-radius: 2px;
}

.kva-from-search {
  margin-bottom: 12px;
  display: flex;

}

.kva-page {
  margin-top: 15px;
  padding: 15px;
  display: flex;
  justify-content: center
}
</style>
